#if UNITY_IOS
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEditor.iOS.Xcode;
using UnityEngine;

namespace ZhiSe.Editor
{
    internal class SeegIOSBuild
    {
        
        internal static void OnPostprocessBuild(string gid, string pf, JObject cfg)
        {
            var resDir = $"{SeegUtil.GetCfgDir()}/{(gid.EndsWith("_") ? pf : gid)}";
            var sdkParamPath = $"{resDir}/seeg_sdk_param.json";
            if (!File.Exists(sdkParamPath))
            {
                Debug.LogError($"[SEEG] seeg_sdk_param.json文件不存在，请检查路径：{sdkParamPath}");
                return;
            }
            var sdkParamObj = JObject.Parse(File.ReadAllText(sdkParamPath));
            JObject info;
            if (!sdkParamObj.ContainsKey("info"))
            {
                info = new JObject();
            }
            else
            {
                info = (JObject)sdkParamObj["info"];
            }
            foreach (var item in cfg)
            {
                info![item.Key] = item.Value;
            }
            sdkParamObj["info"] = info;
            File.WriteAllText(sdkParamPath, sdkParamObj.ToString(Formatting.None));
            var projPath = PBXProject.GetPBXProjectPath(SeegBuild.OutputPath);
            var proj = new PBXProject();
            proj.ReadFromFile(projPath);

            // 获取主 target GUID（Unity 2021+推荐用 GetUnityMainTargetGuid()）
#if UNITY_2019_3_OR_NEWER
            var target = proj.GetUnityMainTargetGuid();
#else
            var target = proj.TargetGuidByName("Unity-iPhone");
#endif
            
            // 添加 seeg_sdk_param.json
            const string sdkParmJsonFile = "seeg_sdk_param.json";
            if (File.Exists(sdkParamPath))
            {
                File.Copy(sdkParamPath, Path.Combine(SeegBuild.OutputPath, sdkParmJsonFile), true);
                var jsonFileGuid = proj.AddFile(sdkParmJsonFile, sdkParmJsonFile);
                proj.AddFileToBuild(target, jsonFileGuid);
            }
            
            // 添加 GoogleService-Info.plist
            const string gsPlistFile = "GoogleService-Info.plist";
            var googlePlistPath = Path.Combine(resDir, gsPlistFile);
            if (File.Exists(googlePlistPath))
            {
                File.Copy(googlePlistPath, Path.Combine(SeegBuild.OutputPath, gsPlistFile), true);
                var plistFileGuid = proj.AddFile(gsPlistFile, gsPlistFile);
                proj.AddFileToBuild(target, plistFileGuid);
            }
            
            // 完成proj配置
            proj.WriteToFile(projPath);

            // 添加Podfile
            var podFilePath = Path.Combine(resDir, "Podfile");
            if (File.Exists(podFilePath))
            {
                File.Copy(podFilePath, Path.Combine(SeegBuild.OutputPath, "Podfile"), true);
            }
            
            // 修改 Info.plist
            var plistPath = Path.Combine(SeegBuild.OutputPath, "Info.plist");
            var plist = new PlistDocument();
            plist.ReadFromFile(plistPath);
            var rootDict = plist.root;
            var infoPath = Path.Combine(resDir, "info.json");
            if (File.Exists(infoPath))
            {
                // 读取info.json内容
                var infoJson = File.ReadAllText(infoPath);
                // 用Dictionary解析
                var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(infoJson);
                Add2PlistDict(rootDict, dict);
            }
            rootDict.SetBoolean("FacebookAdvertiserIDCollectionEnabled", true);
            rootDict.SetBoolean("FacebookAutoLogAppEventsEnabled", true);
            rootDict.SetString("NSUserTrackingUsageDescription", "We need your authorization to provide you with a personalized gaming experience.");
            rootDict.SetString("NSAdvertisingAttributionReportEndpoint", "https://adjust-skadnetwork.com");
            plist.WriteToFile(plistPath);
            
            // 修改 UnityAppController.mm 文件
            try
            {
                var appControllerPath = Path.Combine(SeegBuild.OutputPath, "Classes", "UnityAppController.mm");
                if (!File.Exists(appControllerPath))
                {
                    Debug.LogError("[SEEG] 找不到 UnityAppController.mm 文件！");
                    return;
                }
                var lines = File.ReadAllLines(appControllerPath).ToList();
                var alreadyInjectedImport = false;

                const string importCode = "#import <SeegBridge/SeegBridgeSDK.h>";
                const string matchLine = "[self selectRenderingAPI];";
                string[] executorCodeLines =
                {
                    "    [SeegBridgeSDK registerCSExecutor:^(NSString * _Nonnull gameObject, NSString * _Nonnull funcName, NSString * _Nonnull params) {",
                    "        UnitySendMessage(\"SeegSdkUnityMono\", [funcName UTF8String], [params UTF8String]);",
                    "    }];"
                };
                // === 插入 #import ===
                
                // 先检测是否已插入
                foreach (var t in lines)
                {
                    if (!t.Contains(importCode)) continue;
                    alreadyInjectedImport = true;
                    break;
                }
                // 没有插入则插入
                if (!alreadyInjectedImport)
                {
                    for (var i = 0; i < lines.Count; i++)
                    {
                        if (!lines[i].StartsWith("#import")) continue;
                        lines.Insert(i + 1, importCode);
                        break;
                    }
                }

                // === 插入 executor 到指定代码前 ===
                for (var i = 0; i < lines.Count; i++)
                {
                    if (!lines[i].Contains(matchLine)) continue;
                    var alreadyHasExecutor = lines.Skip(Math.Max(0, i - 3)).Take(5).Any(l => l.Contains("registerCSExecutor"));
                    if (!alreadyHasExecutor)
                    {
                        lines.InsertRange(i, executorCodeLines);
                        File.WriteAllLines(appControllerPath, lines);
                    }
                    break;
                }
                
               
            }
            catch (Exception e)
            {
                Debug.LogError($"[SEEG] 修改 UnityAppController.mm 异常: {e.Message}");
            }
            // 自动运行 pod install
            if (!cfg.ContainsKey("podInstall"))
            {
                return;
            }
            if (!(bool)cfg["podInstall"])
            {
                return;
            }
            try
            {
                var podProcess = new System.Diagnostics.Process();
                podProcess.StartInfo.FileName = "/bin/bash";
                podProcess.StartInfo.Arguments = $"-c \"export LANG=en_US.UTF-8 && cd '{SeegBuild.OutputPath}' && pod install\"";
                podProcess.StartInfo.UseShellExecute = false;
                podProcess.StartInfo.RedirectStandardOutput = true;
                podProcess.StartInfo.RedirectStandardError = true;

                podProcess.Start();
                var output = podProcess.StandardOutput.ReadToEnd();
                var error = podProcess.StandardError.ReadToEnd();
                podProcess.WaitForExit();

                if (podProcess.ExitCode != 0)
                {
                    Debug.LogError($"[SEEG] pod install 失败（ExitCode={podProcess.ExitCode}）：\n{error}");
                }
            }
            catch (Exception e)
            {
                Debug.LogError("[SEEG] 执行 pod install 异常: " + e.Message);
            }
        }
        
        private static void Add2PlistArray(PlistElementArray plistArray, List<object> array)
        {
            foreach (var item in array)
            {
                switch (item)
                {
                    case string str:
                        plistArray.AddString(str);
                        break;
                    case JObject jObj:
                        var plistDict2 = plistArray.AddDict();
                        Add2PlistDict(plistDict2, jObj.ToObject<Dictionary<string, object>>());
                        break;
                    case Dictionary<string, object> dict:
                    {
                        var plistDict = plistArray.AddDict();
                        Add2PlistDict(plistDict, dict);
                        break;
                    }
                    case JArray array2:
                        var arr2 = plistArray.AddArray();
                        Add2PlistArray(arr2, array2.ToObject<List<object>>());
                        break;
                    case List<object> list2:
                    {
                        var plistArray2 = plistArray.AddArray();
                        Add2PlistArray(plistArray2, list2);
                        break;
                    }
                }
            }
        }


        private static void Add2PlistDict(PlistElementDict plistDict, Dictionary<string, object> dict)
        {
            foreach (var item in dict)
            {
                switch (item.Value)
                {
                    case string str:
                        plistDict.SetString(item.Key, str);
                        break;
                    case JArray array:
                        var arr2 = plistDict.CreateArray(item.Key);
                        Add2PlistArray(arr2, array.ToObject<List<object>>());
                        break;
                    case List<object> list:
                    {
                        var arr = plistDict.CreateArray(item.Key);
                        Add2PlistArray(arr, list);
                        break;
                    }
                    case JObject dict3:
                        var plistDict3 = plistDict.CreateDict(item.Key);
                        Add2PlistDict(plistDict3, dict3.ToObject<Dictionary<string, object>>());
                        break;
                    case Dictionary<string, object> dict2:
                    {
                        var plistDict2 = plistDict.CreateDict(item.Key);
                        Add2PlistDict(plistDict2, dict2);
                        break;
                    }
                }
            }
            
        }

    }
}
#endif